/**
 * Created with JetBrains WebStorm.
 * User: rren
 * Date: 19/08/13
 * Time: 15:55
 * To change this template use File | Settings | File Templates.
 */

var fs = require('fs');
var zlib = require('zlib');

exports.exists = function(FileName, callback) {

    fs.exists(FileName, function (exist) {
        if(exist){
            //console.log("The requested file is existed!");
            callback(exist);
        }else{
            //console.log("The requested file is NOT existed!");
            callback(exist);
        }
    })
};

exports.read = function(FileName, callback) {
    fs.readFile(FileName, "binary", function(error, file) {
        callback(error, file);
    })
};

exports.status = function(FileName, callback) {
    fs.stat(FileName, function(error, stat){
        callback(error, stat);
    })
};

exports.readFileStream = function(FileName,start, end, mode, request, response, callBack) {
    //console.log("Request ["+FileName+"]:range:"+start+"-"+end);


    var ext = path.extname(FileName);
    ext = ext ? ext.slice(1) : "unknown";



    var raw = fs.createReadStream(FileName, {start:start, end: end});

    if(mode == "gzip") {
        //console.log("WriteStream mode gzip");
        raw.pipe(zlib.createGzip()).pipe(response);
    } else if ( mode == "deflate"){
        //console.log("WriteStream mode deflate");
        raw.pipe(zlib.createDeflate()).pipe(response);
    } else {
        //console.log("WriteStream mode raw");
        raw.pipe(response);
    }

    response.on('finish', function () {
        //console.log("---Write file:["+FileName+"]range:"+start+"-"+end+" completed.---");
        callBack();
    });
};




